package com.five.config;

import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

import javax.annotation.PreDestroy;

@Configuration
public class RocketMQConfig {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    private TransactionMQProducer transactionMQProducer;

    @Bean("addCollectRocketMQTemplate")
    public RocketMQTemplate addCollectRocketMQTemplate() {
        transactionMQProducer = new TransactionMQProducer(producerGroup);
        transactionMQProducer.setNamesrvAddr(nameServer);
        transactionMQProducer.setSendMsgTimeout(3000);
        transactionMQProducer.setRetryTimesWhenSendFailed(2);

        RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
        rocketMQTemplate.setProducer(transactionMQProducer);

        // 关键：配置消息转换器，将对象序列化为 JSON 字符串
        rocketMQTemplate.setMessageConverter(new MappingJackson2MessageConverter());

        return rocketMQTemplate;
    }

    @PreDestroy
    public void destroy() {
        if (transactionMQProducer != null) {
            transactionMQProducer.shutdown();
        }
    }
}